'use client';
import React, { useEffect, useState, useContext } from 'react';
import { Table, Button, Modal, Form, Input, Space, Popconfirm } from 'antd';
import { EditOutlined, ReloadOutlined } from '@ant-design/icons';
import { useRouter } from 'next/navigation';
import { projectApi } from '@/services/projectApi';
import { MessageApiContext } from '../layout/MainLayout';

const Project: React.FC = () => {
  const [projects, setProjects] = useState<any[]>([]);
  const [editing, setEditing] = useState<any>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const PAGE_SIZE = 10;
  const router = useRouter();
  const messageApi = useContext(MessageApiContext);

  const fetchProjects = async (pageNum = page) => {
    setLoading(true);
    try {
      const res = await projectApi.getProjects({ page: pageNum, page_size: PAGE_SIZE });
      setProjects(res.data?.Data || []);
      setTotal(res.data?.TotalCount || 0);
      console.log('projects:', res.data?.Data);
    } catch (e) {
      messageApi.error('获取项目列表失败');
      console.log('error:', e);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProjects(1);
  }, []);

  const handleTableChange = (pagination: any) => {
    setPage(pagination.current);
    fetchProjects(pagination.current);
  };

  const handleEdit = (record: any) => {
    setIsModalVisible(true);
    setTimeout(() => {
      setEditing(record);
      form.setFieldsValue({ ProjectName: record.ProjectName });
    }, 1);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      console.log('values:', values);
      await projectApi.updateProject(editing.ID, {
        ...editing,
        ...values
      });
      messageApi.success('编辑成功');
      setIsModalVisible(false);
      fetchProjects(page);
    } catch (err: any) {
      messageApi.error(err?.response?.data?.message || err?.message || '编辑失败');
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await projectApi.deleteProject(id);
      messageApi.success('删除成功');
      fetchProjects(page);
    } catch (err: any) {
      messageApi.error(err?.response?.data?.message || err?.message || '删除失败');
    }
  };

  const projectColumns = [
    { title: '编号', dataIndex: 'ID', key: 'ID', width: 80 },
    { title: '项目名称', dataIndex: 'ProjectName', key: 'ProjectName', render: (text: string, record: any) => <a onClick={() => router.push(`/project/${record.ID}`)}>{text}</a> },
    { title: '扫描条数', dataIndex: 'ScanCount', key: 'ScanCount', width: 100 },
    { title: '状态', dataIndex: 'Status', key: 'Status', width: 100, render: (Status: number) => Status === 1 ? '已完成' : '扫描中' },
    { title: '创建时间', dataIndex: 'CreateTime', key: 'CreateTime', width: 180, render: (t: string) => new Date(t).toLocaleString() },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space>
          <Button icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)}>编辑</Button>
          <Popconfirm title="确定删除该项目吗？" onConfirm={() => handleDelete(record.ID)}>
            <Button danger size="small">删除</Button>
          </Popconfirm>
        </Space>
      ),
      width: 140,
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', marginBottom: 16 }}>
        <Button
          type="text"
          icon={<ReloadOutlined />}
          onClick={() => fetchProjects(page)}
          loading={loading}
          aria-label="刷新"
        />
      </div>
      <Table
        rowKey="ID"
        columns={projectColumns}
        dataSource={projects}
        loading={loading}
        pagination={{ current: page, pageSize: PAGE_SIZE, total, showSizeChanger: false }}
        onChange={handleTableChange}
      />
      <Modal
        title="编辑项目名称"
        open={isModalVisible}
        onOk={handleOk}
        onCancel={() => setIsModalVisible(false)}
        destroyOnHidden
      >
        <Form form={form} layout="vertical" preserve={false}>
          <Form.Item name="ProjectName" label="项目名称" rules={[{ required: true, message: '请输入项目名称' }]}> 
            <Input /> 
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Project; 